package com.yao.longhan.ui.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.support.design.widget.FloatingActionButton;

import android.view.View;
import android.view.WindowManager;
import android.widget.AbsoluteLayout;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.yao.longhan.R;
import com.yao.longhan.adapter.ShelfAdapter;
import com.yao.longhan.animation.ContentScaleAnimation;
import com.yao.longhan.animation.Rotate3DAnimation;
import com.yao.longhan.constant.Config;
import com.yao.longhan.db.BookList;
import com.yao.longhan.eventbus.AddToShelfEvent;
import com.yao.longhan.eventbus.RxEvent;
import com.yao.longhan.filechooser.FileChooserActivity;
import com.yao.longhan.ui.activity.ReadActivity;
import com.yao.longhan.ui.base.BaseFragment;
import com.yao.longhan.view.DragGridView;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.util.List;

import butterknife.BindView;

/**
 * Created by CAIYAO on 2017/7/24.
 */

public class HomeFragment1 extends BaseFragment {

    @BindView(R.id.bookShelf)
    DragGridView bookShelf;
    @BindView(R.id.fab)
    FloatingActionButton fab;
    private Config config;
    private WindowManager mWindowManager;
    private View rootView;
    private AbsoluteLayout wmRootView;
    private Typeface typeface;
    private List<BookList> bookLists;
    private ShelfAdapter adapter;
    private int itemPosition;
    //点击书本在屏幕中的x，y坐标
    private int[] location = new int[2];
    private TextView itemTextView;
    private static TextView cover;
    private static ImageView content;
    //书本打开动画缩放比例
    private float scaleTimes;
    //书本打开缩放动画
    private static ContentScaleAnimation contentAnimation;
    private static Rotate3DAnimation coverAnimation;
    //书本打开缩放动画持续时间
    public static final int ANIMATION_DURATION = 800;
    //打开书本的第一个动画是否完成
    private boolean mIsOpen = false;
    //动画加载计数器  0 默认  1一个动画执行完毕   2二个动画执行完毕
    private int animationCount = 0;

    private static Boolean isExit = false;


    @Override
    protected int layoutId() {
        return R.layout.app_bar_main;
    }

    @Override
    protected void initAfter() {
        config = Config.getInstance();

        // 删除窗口背景
        mActivity.getWindow().setBackgroundDrawable(null);
        mWindowManager = (WindowManager) mActivity.getSystemService(Context.WINDOW_SERVICE);
        wmRootView = new AbsoluteLayout(mActivity);
        rootView = mActivity.getWindow().getDecorView();
//        SQLiteDatabase db = Connector.getDatabase();  //初始化数据库
        typeface = config.getTypeface();
        bookLists = DataSupport.findAll(BookList.class);
        adapter = new ShelfAdapter(mActivity, bookLists);
        bookShelf.setAdapter(adapter);
        loadData();
    }

    private void loadData() {
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
                Intent intent = new Intent(mActivity, FileChooserActivity.class);
                mActivity.startActivity(intent);
            }
        });


        bookShelf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (bookLists.size() > position) {
                    itemPosition = position;
                    String bookname = bookLists.get(itemPosition).getBookname();

                    adapter.setItemToFirst(itemPosition);
//                bookLists = DataSupport.findAll(BookList.class);
                    final BookList bookList = bookLists.get(itemPosition);
                    bookList.setId(bookLists.get(0).getId());
                    final String path = bookList.getBookpath();
                    File file = new File(path);
                    if (!file.exists()) {
                        new AlertDialog.Builder(mActivity)
                                .setTitle(mActivity.getString(R.string.app_name))
                                .setMessage(path + "文件不存在,是否删除该书本？")
                                .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        DataSupport.deleteAll(BookList.class, "bookpath = ?", path);
                                        bookLists = DataSupport.findAll(BookList.class);
                                        adapter.setBookList(bookLists);
                                    }
                                }).setCancelable(true).show();
                        return;
                    }

                    ReadActivity.openBook(bookList, mActivity);
                }
            }
        });
    }

    @Override
    protected void onEventMainThread(RxEvent rxEvent) {
        if (rxEvent instanceof AddToShelfEvent) {
            loadData();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        DragGridView.setIsShowDeleteButton(false);
        bookLists = DataSupport.findAll(BookList.class);
        adapter.setBookList(bookLists);
        closeBookAnimation();
    }

    public void closeBookAnimation() {

        if (mIsOpen && wmRootView != null) {
            //因为书本打开后会移动到第一位置，所以要设置新的位置参数
            contentAnimation.setmPivotXValue(bookShelf.getFirstLocation()[0]);
            contentAnimation.setmPivotYValue(bookShelf.getFirstLocation()[1]);
            coverAnimation.setmPivotXValue(bookShelf.getFirstLocation()[0]);
            coverAnimation.setmPivotYValue(bookShelf.getFirstLocation()[1]);

            AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams(
                    itemTextView.getLayoutParams());
            params.x = bookShelf.getFirstLocation()[0];
            params.y = bookShelf.getFirstLocation()[1];//firstLocation[1]在滑动的时候回改变,所以要在dispatchDraw的时候获取该位置值
            wmRootView.updateViewLayout(cover, params);
            wmRootView.updateViewLayout(content, params);
            //动画逆向运行
            if (!contentAnimation.getMReverse()) {
                contentAnimation.reverse();
            }
            if (!coverAnimation.getMReverse()) {
                coverAnimation.reverse();
            }
            //清除动画再开始动画
            content.clearAnimation();
            content.startAnimation(contentAnimation);
            cover.clearAnimation();
            cover.startAnimation(coverAnimation);
        }
    }


    @Override
    public void onStop() {
        DragGridView.setIsShowDeleteButton(false);
        super.onStop();
    }

    @Override
    public void onDestroy() {
        DragGridView.setIsShowDeleteButton(false);
        super.onDestroy();
    }

}
